<template>
  <div class="main">
    <!-- 左侧菜单 -->
    <div class="sidebar">
      <div class="logo">
        <img src="@/assets/Logo.png" alt="Logo" />
      </div>
      <ul class="menu">
        <li>
          <router-link to="/personalcenter">个人中心</router-link>
        </li>
        <li>
          <router-link to="/viewrecording">浏览记录</router-link>
        </li>
        <li class="parent-menu" :class="{ active: isSubmenuOpen }" @click="toggleSubmenu">
          <a href="#" class="parent-link">账户设置
            <span class="toggle-icon">^</span>
          </a>
          <ul class="submenu">
            <li><router-link to="/personalinfo">个人资料</router-link></li>
            <li><router-link to="/preference-settings">偏好设置</router-link></li>
          </ul>
        </li>
      </ul>
    </div>

    <!-- 右侧内容 -->
    <div class="content">
      <div class="content-header">
        <div style="display: flex; align-items: center;">
          <img :src="userStore.info?.icon || defaultAvatar" alt="用户头像" class="avatar" />
          <span class="username">{{ userStore.userName || '用户名' }}</span>
        </div>
        <!-- 返回主页按钮 -->
        <router-link to="/home" class="home-button">返回主页</router-link>
      </div>

      <!-- 个人资料表单 -->
      <div class="profile-form">
        <div class="form-item">
          <label>当前头像</label>
          <div class="avatar-preview">
            <img :src="userInfo.icon || defaultAvatar" alt="当前头像" @error="handleImageError" />
          </div>
          <div class="avatar-actions">
            <input 
              type="file" 
              ref="fileInput" 
              accept="image/*" 
              style="display: none" 
              @change="handleFileChange" 
            />
            <button class="change-avatar-btn" @click="triggerFileUpload">上传图片</button>
          </div>
        </div>

        <div class="form-item">
          <label>用户名</label>
          <input type="text" v-model="userInfo.userName" placeholder="请输入用户名" />
        </div>

        <div class="form-item">
          <label>手机号</label>
          <input type="text" v-model="userInfo.phone" placeholder="请输入手机号" />
        </div>

        <div class="form-item">
          <label>生日</label>
          <input type="date" v-model="userInfo.birthdate" placeholder="请选择生日" />
        </div>

        <div class="form-item">
          <label>性别</label>
          <div class="gender-options">
            <label>
              <input type="radio" v-model="userInfo.gender" value="男" />
              男
            </label>
            <label>
              <input type="radio" v-model="userInfo.gender" value="女" />
              女
            </label>
            <label>
              <input type="radio" v-model="userInfo.gender" value="保密" />
              保密
            </label>
          </div>
        </div>

        <div class="form-item">
          <button class="save-btn" @click="saveProfile" :disabled="isLoading">
            {{ isLoading ? '保存中...' : '保存' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getCurrentUser, updateUserInfo, uploadFile } from '@/api';
import { useUserStore } from '@/stores/user';
import defaultAvatarImg from '@/assets/user.svg';

const userStore = useUserStore();
const isSubmenuOpen = ref(true); // 默认展开账户设置
const defaultAvatar = defaultAvatarImg;
const fileInput = ref(null);
const isLoading = ref(false);

const toggleSubmenu = () => {
  isSubmenuOpen.value = !isSubmenuOpen.value;
};

// 用户数据
const userInfo = ref({
  userId: null,
  userName: '',
  gender: '保密',
  icon: '',
  phone: '',
  birthdate: ''
});

// 格式化日期：YYYYMMDD -> YYYY-MM-DD
const formatDateForInput = (dateStr) => {
  if (!dateStr || dateStr.length !== 8) return dateStr;
  return `${dateStr.substring(0, 4)}-${dateStr.substring(4, 6)}-${dateStr.substring(6, 8)}`;
};

// 格式化日期：YYYY-MM-DD -> YYYYMMDD
const formatDateForSubmit = (dateStr) => {
  if (!dateStr) return '';
  return dateStr.replace(/-/g, '');
};

// 获取当前用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getCurrentUser();
    if (res.data) {
      const data = res.data;
      userInfo.value = {
        userId: data.userId,
        userName: data.userName || data.username || '', // 兼容不同字段名
        gender: data.gender || '保密',
        icon: data.icon || '',
        phone: data.phone || '',
        birthdate: formatDateForInput(data.birthdate || '')
      };
    }
  } catch (error) {
    console.error('获取用户信息失败', error);
  }
};

// 触发文件选择
const triggerFileUpload = () => {
  fileInput.value.click();
};

// 处理文件选择
const handleFileChange = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  try {
    isLoading.value = true;
    const res = await uploadFile(file);
    if (res.data) {
      const url = res.data;
      userInfo.value.icon = url;
      
      // 自动保存头像到数据库
      if (userInfo.value.userId) {
        try {
          const updateData = {
            icon: url
          };
          
          await updateUserInfo(userInfo.value.userId, updateData);
          
          // 更新本地 Store
          userStore.setUserInfo({
            ...userStore.info,
            icon: url
          });
          
          alert('头像上传并保存成功！');
        } catch (saveError) {
          console.error('保存头像失败', saveError);
          alert('头像上传成功但保存失败，请手动保存');
        }
      } else {
        alert('图片上传成功，请点击保存按钮保存');
      }
    }
  } catch (error) {
    console.error('上传失败', error);
    alert('图片上传失败，请重试');
  } finally {
    isLoading.value = false;
    // 清空 input 以允许重复上传同一文件
    if (fileInput.value) fileInput.value.value = '';
  }
};

// 图片加载失败处理
const handleImageError = (e) => {
  e.target.src = defaultAvatar;
};
// 保存逻辑
const saveProfile = async () => {
  if (!userInfo.value.userId) {
    alert('用户信息未加载');
    return;
  }
  
  try {
    isLoading.value = true;
    const updateData = {
      userName: userInfo.value.userName,
      gender: userInfo.value.gender,
      icon: userInfo.value.icon,
      phone: userInfo.value.phone,
      birthdate: formatDateForSubmit(userInfo.value.birthdate)
    };
    
    await updateUserInfo(userInfo.value.userId, updateData);
    
    // 立即更新本地 Store，确保界面即时刷新
    userStore.setUserInfo({
      ...userStore.info,
      ...updateData
    });
    
    alert('个人信息已保存！');
  } catch (error) {
    console.error('保存失败', error);
    alert('保存失败：' + (error.message || '未知错误'));
  } finally {
    isLoading.value = false;
  }
};

onMounted(() => {
  fetchUserInfo();
});
</script>

<style scoped>
@import '@/CSS/UserPublicCss.css';
@import '@/CSS/PersonalInfo.css';
</style>